import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios";
import userStore from "@/store/modules/user";
import {  ElMessage } from "element-plus";
import router from "@/router";
const service = axios.create({
    baseURL: import.meta.env.VITE_SERVICE_API,
    timeout: 50000,
    headers: { "Content-Type": "application/json;charset=utf-8" },
});
//拦截请求，给请求加上userToken
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        const useUserStore = userStore()
        if (useUserStore.getUserToken) {
            config.headers['BS-WEB-TOKEN'] = useUserStore.getUserToken;
        }
        return config;
    },
    (error: any) => {
        return Promise.reject(error);
    }
);

//拦截响应
service.interceptors.response.use(
    (response: AxiosResponse) => {
        const { code, message } = response.data;
        if (code === 200) {
            if(message){
                ElMessage.success(message);
            }
            return response.data;
        }
        ElMessage.error(message || "系统出错");
        return Promise.reject(new Error(message || "Error"));
    },
    (error: any) => {
        switch (error.response.status) {
            case 400:
                ElMessage.error("请求错误(400)");
                break;
            case 401:
                const useUserStore = userStore()
                useUserStore.LOGOUT()
                ElMessage.error("未授权，请重新登录(401)");
                router.push({ path: "/login" })
                break;
            case 403:
                ElMessage.error("拒绝访问(403)");
                break;
            case 404:
                ElMessage.error("请求出错(404)");
                break;
            case 408:
                ElMessage.error("请求超时(408)");
                break;
            case 500:
                ElMessage.error("服务器错误(500)");
                break;
            case 501:
                ElMessage.error("服务未实现(501)");
                break;
            case 502:
                ElMessage.error("网络错误(502)");
                break;
            case 503:
                ElMessage.error("服务不可用(503)");
                break;
            case 504:
                ElMessage.error("网络超时(504)");
                break;
            case 505:
                ElMessage.error("HTTP版本不受支持(505)");
                break;
            default: {
                ElMessage.error(`连接出错(${error.response.status})!`);
            }
        }
        return error;
    }
);
export default service;
